<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use \think\Request;
use think\facade\View;
use app\common\model\ProductOrder as ProductOrderModel;
use app\common\model\ProductOrderList;
use app\common\model\User;
use app\common\model\Delivery;
use app\common\model\ProductNorms;
use app\common\model\Product;
use think\facade\Db;

class ProductOrder extends Base
{
	/**
	 * 订单列表
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function index(Request $request){
		$keyword=trim(input('get.keyword'));
		$status=trim(input('get.status'));
		$start_time=trim(input('get.start_time'));
		$end_time=trim(input('get.end_time'));
		$whe=array();
		if(!empty($keyword)){
			$whe[] = ['order_num','like','%'.$keyword.'%'];
		}
		if(!empty($status)){
			$whe[] = ['status','=',$status];
		}

		if(!empty($end_time)){			
			$end_time = strtotime($end_time) + 86399;
		}else{
			$end_time=time();
		}
		if(!empty($start_time)){
			$start_time=strtotime($start_time);
			if($start_time>$end_time){
				$this->error('开始时间不能大于结束时间');
			}
			$whe[] = ['addtime','BETWEEN',array($start_time,$end_time)];
		}else{
			$whe[] = ['addtime','<',$end_time];
		}
		
		$data = ProductOrderModel::getList($whe,'*','id desc',$this->page);
		foreach($data['list'] as $k=>&$v){
			$v['mobile'] = User::where(['id'=>$v['user_id']])->value('nickname');
			$product = ProductOrderList::getInfo(['order_id'=>$v['id']],'title,imgurl');
			$v['title'] = $product['title'];
			$v['imgurl'] = $product['imgurl'];
		}
       
		View::assign('list',$data['list']);
		View::assign('count',$data['count']);
		View::assign('page',$data['page']);
		return View::fetch("ProductOrder/index");
	}

	/**
	 * 订单详情
	 */
	public function detail(Request $request){
		$id = $request->param('id');
		$whe[] = ['id','=',$id];
		$orderlist = ProductOrderModel::getInfo($whe,'*');
		$product = ProductOrderList::getAllList(['order_id'=>$id],'*');
		foreach ($product as $k => $v) {
			if(!empty($v['sku']) && $v['order_type'] ==1){
				$sku_arr = explode(',',trim($v['sku'],','));
				$sku_count = count($sku_arr);
				$norms_count = ProductNorms::where(['product_id'=>$v['product_id']])->count();
				$attr_sku = [];
				foreach ($sku_arr as $key => $val) {
					$w=[];
					$w[] = ['product_id','=',$v['product_id']];
					$w[] = ['norms_values','like','%'.$val.'%'];
					$norms_name = ProductNorms::where($w)->value("norms_name");
					$attr_sku[$key] = $norms_name.'：'.$val;
				}
				$v['sku'] = $attr_sku;
			}
			if ($v['order_type'] == '4') {
			    $v['price'] = $v['price'] . ' : 钻石';
            }
		}
		
		$user = User::getInfo(['id'=>$orderlist['user_id']],'id,nickname,mobile,headimg');
		$orderlist['user_mobile'] = $user['nickname'];

		View::assign("orderlist",$orderlist);
		View::assign("product",$product);
	
		return View::fetch('ProductOrder/detail');
	}

	/**
	 * 发货
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function send(Request $request){
		if(!$request->isPost()){
			$id=$request->param("id");
			$order_num = ProductOrderModel::where(['id'=>$id])->value("order_num");
		    $delivery = Delivery::select();

			View::assign("order_num",$order_num);
			View::assign("id",$id);
            View::assign("delivery", $delivery);
			return View::fetch('ProductOrder/send');
		}else{
			$courier_name=$request->param("courier_name");
			$courier_number=$request->param("courier_number");
			if(empty($courier_name)){
				return $this->renderError("请选择物流名称");
			}
			if(empty($courier_number)){
				return $this->renderError("请输入物流单号");
			}
			$delivery_info = Delivery::where(['id' => $courier_name])->find();
            if (!$delivery_info) {
                return $this->renderError("物流公司选择错误");
            }
			$order_id=$request->param("id");
			$res = ProductOrderModel::where(array("id"=>$order_id))->field("id,status,order_num")->find();
			if($res['status']=='1'){
				return $this->renderError("该订单未支付");
			}elseif ($res['status']==3) {
				return $this->renderError("订单已发货");
			}elseif ($res['status']==4) {
				return $this->renderError("订单已完成");
			}elseif ($res['status']==5) {
				return $this->renderError("订单已取消");
			}
			ProductOrderModel::startTrans();
			$data['status']=3;
			$data['fa_time']=time();
			$data['courier_name'] = $delivery_info['name'];
			$data['courier_number']=$courier_number;
			$data['courier_code'] = $delivery_info['code'];
			$ol=ProductOrderModel::where(array("id"=>$order_id))->update($data);
			$oo = ProductOrderList::where(array("order_id"=>$order_id))->update(['status'=>'3']);
			if($ol && $oo){
				ProductOrderModel::commit();
				return $this->renderSuccess("发货成功，请等待客户签收");
			}else{
				ProductOrderModel::rollback();
				return $this->renderError("网络繁忙，请稍后");
				
			}
		}
	}


    /**
     * 发货订单取消
     */
    public function cancel_product_order()
    {
        $id = request()->param('id/d', 0);
        $info = ProductOrderModel::where('id', '=', $id)->find();
        $orderInfoList = ProductOrderList::where(['order_id' => $info['id']])->find();

        if (!$info) {
            return $this->renderError('请求参数错误');
        }
        if (!in_array($info['status'], [2, 3]) ) {
            return $this->renderError('此订单不能取消');
        }
        Db::startTrans();
        $res = [];
        if ($info['total'] > 0) {
            $wxServer = new \app\common\server\WechatRefund($this->app);
            $refund_res = $wxServer->OrderRefund1($info['total'], $info['order_num']);
            if ($refund_res['status'] == 1) {
                $res[] = Db::name('wxpay_log')->insert([
                    'order_no' => 'QX_' . $info['order_num'],
                    'content' => json_encode($refund_res['msg']),
                    'type' => 2,
                    'addtime' => time()
                ]);
            }
        }
        
        if ($info['use_money'] > 0) {
            User::changeMoney($info['user_id'], $info['use_money'], 6,'订单取消退回');
        }
        //修改订单状态
        $res[] = Db::name('product_order')->where('id', $info['id'])->update(['status' => 5, 'update_time' => time()]);
        $res[] = Db::name('product_order_list')->where('order_id', $info['id'])->update(['status' => 5]);  //  取消

        //修改商品销量和库存
        $res[] = Db::name('product')->where('id', $orderInfoList['product_id'])->inc('stock', 1)->dec('sales', 1)->update();
        $res[] = Db::name('product_norms_value')->where('sku', $orderInfoList['sku'])->where('product_id', $orderInfoList['product_id'])->inc('stock', 1)->dec('sales', 1)->update();
        if (resCheck($res)) {
            Db::commit();
            return $this->renderSuccess('取消成功');
        } else {
            Db::rollback();
            return $this->renderError('取消失败');
        }
    }

	/**
	 * 订单信息导出
	 */
	//导出
	public function productorderchu(Request $request){
		set_time_limit(0);
        ini_set('memory_limit','1024M');
// 		require_once '../extend/PHPExcel/PHPExcel.php';
        $save_name = substr(dirname($_SERVER['SCRIPT_FILENAME']), 0, -6);
		require $save_name . 'extend/phpexcel/PHPExcel.php';

		$objPHPExcel = new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); 
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20); 
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30); 
        //设置行高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25);
        //set font size bold
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('A2:I2')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A2:I2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A2:I2')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        //设置水平居中
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); 
        $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); 
        $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); 
        //合并cell
        $objPHPExcel->getActiveSheet()->mergeCells('A1:I1');

        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '商品订单信息统计:'.date('Y-m-d H:i:s'))
            ->setCellValue('A2', '订单ID')
            ->setCellValue('B2', '订单号')
            ->setCellValue('C2', '商品名称')
            ->setCellValue('D2', '商品数量')
            ->setCellValue('E2', '用户手机号')
            ->setCellValue('F2', '收货信息')
            ->setCellValue('G2', '订单状态')
            ->setCellValue('H2', '物流名称') 
            ->setCellValue('I2', '物流单号');  
        // Miscellaneous glyphs, UTF-8
        $whe=[];
        $keyword = $request->param("keyword");
        $status = $request->param("status");
        $start_time = $request->param("start_time");
        $end_time = $request->param("end_time");
        if(empty($status) || empty($start_time) || empty($end_time)){
        	// $this->error('请选择导出状态和时间范围');
        }
        
        $t = strtotime($end_time)-strtotime($start_time);
        $tt = 86400*30;
        if($t > $tt){
        	$this->error('最多导出30天内的数据');
        }
        if(!empty($keyword)){
        	$whe[] = ['order_num','like','%'.$keyword.'%'];
        }
        if(!empty($status)){
        	$whe[] = ['status','=',$status];
        }else{
        	$whe[] = ['status','=','2'];
        }
        if(!empty($end_time)){			
			$end_time = strtotime($end_time) + 86399;
		}else{
			$end_time=time();
		}
		if(!empty($start_time)){
			$start_time=strtotime($start_time);
			if($start_time>$end_time){
				$this->error('开始时间不能大于结束时间');
			}
			$whe[] = ['addtime','BETWEEN',array($start_time,$end_time)];
		}else{
			$whe[] = ['addtime','<',$end_time];
		}
       $data = ProductOrderModel::getList($whe,'id,order_num,status,name,mobile,province,city,county,address,courier_number,courier_name,user_id','id desc',10000);
        $arr = [];
        $n=0;
        foreach ($data['list'] as $key => &$v) {
			    if($v['status']!=2){
            		unset($data['list'][$key]);
            		continue;
            	}
			$product = ProductOrderList::getAllList(['order_id'=>$v['id']],'title,imgurl,num');	
        	$smobile =  User::where(['id'=>$v['user_id']])->value('mobile');	
			foreach($product as $kk=>$vv){
				$res = [];
				$res = $v;
				$res['smobile'] = $smobile;
				$res['title'] = $vv['title'];
				$res['imgurl'] = $vv['imgurl'];
				$res['num'] = $vv['num'];
				$arr[$n] = $res;
				$n++;
			}
        }
		$list = $data['list'];
		$list = $arr;
        for($i=0;$i<count($list);$i++){        	
        	$status = '';
        	if($list[$i]['status']=='2'){
        		$status = "待发货";
        	}elseif($list[$i]['status']=='3'){
        		$status = "已发货";
        	}elseif($list[$i]['status']=='4'){
        		$status = "已完成";
        	}
        
            $objPHPExcel->getActiveSheet(0)->setCellValue('A'.($i+3), $list[$i]['id']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B'.($i+3), $list[$i]['order_num'].' ');
            $objPHPExcel->getActiveSheet(0)->setCellValue('C'.($i+3), $list[$i]['title']);	   
            $objPHPExcel->getActiveSheet(0)->setCellValue('D'.($i+3), $list[$i]['num']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('E'.($i+3), $list[$i]['smobile']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('F'.($i+3), $list[$i]['name'].'-'.$list[$i]['mobile'].'-'.$list[$i]['province'].$list[$i]['city'].$list[$i]['county'].$list[$i]['address']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('G'.($i+3), $status);
            $objPHPExcel->getActiveSheet(0)->setCellValue('H'.($i+3), $list[$i]['courier_name']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('I'.($i+3), $list[$i]['courier_number']);
            $objPHPExcel->getActiveSheet()->getStyle('A'.($i+3).':G'.($i+3))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getStyle('A'.($i+3).':G'.($i+3))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $objPHPExcel->getActiveSheet()->getRowDimension($i+3)->setRowHeight(50);
        }

        //  sheet命名
        $objPHPExcel->getActiveSheet()->setTitle('商品订单'); 
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0); 
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		// Redirect output to a client’s web browser (Excel2007)
		 /* 生成到浏览器，提供下载 */ 
		 	ob_end_clean();  //清空缓存  
		    header("Pragma: public");
		    header("Expires: 0");
		    header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
		    header("Content-Type:application/force-download");
		    header("Content-Type:application/vnd.ms-execl");
		    header("Content-Type:application/octet-stream");
		    header("Content-Type:application/download");
		    header('Content-Disposition:attachment;filename="商城订单记录.xlsx"');
		    header("Content-Transfer-Encoding:binary"); 
		    $objWriter->save('php://output');
			exit;
	}

}